﻿using UnityEngine;
using System.Collections;

public class chomperScript : MonoBehaviour {
	
	public playerOnTopChecker checkPlayerOnTop;
	public flappingChomper chomperObject;
	
	public bool isAttacking;
	public float attackFrequency = 1.0f;
	public float stayTime = 1.0f;
	public float moveSpeed = 1.0f;
	public float timeCounter = 0;
	
	float topPos;
	float bottomPos;
	float startFlapPos;
	
	int attackPhase = 0;
	
	// Use this for initialization
	void Start () {
		bottomPos = chomperObject.transform.position.y;
		startFlapPos = bottomPos + 1.0f;
		topPos = bottomPos + 1;
		isAttacking = false;
	}
	
	// Update is called once per frame
	void Update () {
		
		if(!isAttacking)
		{
			if(timeCounter < attackFrequency)
			{
				//Debug.Log(timeCounter);
				timeCounter += Time.deltaTime;
			}
			
			if(timeCounter >= attackFrequency)
			{
				if(!checkPlayerOnTop.playerIsOnTop)
				{
					//Debug.Log("ATTAC");
					isAttacking = true;
				}
				timeCounter = 0;
			}
		}
		else
		{
			
			if(attackPhase < 2)
			{
				Vector3 tmpPos = chomperObject.transform.position;
				tmpPos.y += moveSpeed * Time.deltaTime;
				chomperObject.transform.position = tmpPos;
				
				if(attackPhase == 0 && chomperObject.transform.position.y >= startFlapPos)
				{
					chomperObject.doFlap();
					attackPhase = 1;
				}
				else if(attackPhase == 1)
				{
					if(chomperObject.transform.position.y >= topPos)
					{
						tmpPos.y = topPos;
						chomperObject.transform.position = tmpPos;
						
						attackPhase = 2;
					}
				}
			}
			else if(attackPhase == 2)
			{
				timeCounter += Time.deltaTime;
				if(timeCounter > stayTime)
				{
					attackPhase = 3;
					timeCounter = 0;
				}
			}
			else if(attackPhase == 3)
			{
				Vector3 tmpPos = chomperObject.transform.position;
				tmpPos.y -= moveSpeed * Time.deltaTime;
				chomperObject.transform.position = tmpPos;
				
				if(chomperObject.transform.position.y <= bottomPos)
				{
					tmpPos.y = bottomPos;
					chomperObject.transform.position = tmpPos;
					
					attackPhase = 0;
					isAttacking = false;
				}
			}
			//chomperObject.doFlap();
			
		}
	}
}
